﻿//  --------------------------------
//  Copyright (c) 2010 Michael Schuler, Sascha Burger. All rights reserved.
//  This source code is made available under the terms of the Microsoft Public License (Ms-PL)
//  http://p2pmessaging.codeplex.com/license
//  ---------------------------------
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using p2pMessaging.Interfaces;
using p2pMessaging.Interfaces.Contact;

namespace p2pMessaging.BL.Plugin
{
	/// <summary>
	/// Plugin to send and receive messages through ip addresses.
	/// </summary>
	public sealed class P2PMessageService : IMessageService
	{
		private static readonly Guid myPluginId = new Guid("60B4C0B0-112E-47F4-8D9B-841572E8051B");
		
		private const int PORT = 27000;
		
		private readonly ISerializeService mySerializeService;
		private readonly List<IMessage> myReceivedMessages = new List<IMessage>();

		private Thread myReceivingThread;
		private bool myIsRunning;

		public P2PMessageService(ISerializeService serializeService)
		{
			mySerializeService = serializeService;
			beginReceiving();
		}

		/// <summary>
		/// Gets the id of the plugin.
		/// </summary>
		public Guid PluginId
		{
			get { return myPluginId; }
		}
		
		public bool IsThreadRunning
		{
			get { return myIsRunning; }
		}

		/// <summary>
		/// Send a new message with the ip address.
		/// </summary>
		/// <param name="message">Message to send.</param>
		public void Send(IMessage message)
		{
			if (message == null)
			{
				throw new ArgumentNullException("message");
			}

			message.PluginId = myPluginId;

			UdpClient client = new UdpClient();
			client.ExclusiveAddressUse = true;

			byte[] msg = mySerializeService.Serialize(message);

			foreach (IContact recipient in message.Recipient)
			{
				IPAddress address = IPAddress.Parse(recipient.IpAddress);
				IPEndPoint endPoint = new IPEndPoint(address, PORT);
				client.Send(msg, msg.Length, endPoint);
			}

			client.Close();
		}

		/// <summary>
		/// Returns all received messages.
		/// </summary>
		/// <returns>List of messages. Can be empty.</returns>
		public List<IMessage> Receive()
		{
			List<IMessage> result = new List<IMessage>();
			result.AddRange(myReceivedMessages);
			myReceivedMessages.Clear();
			return result;
		}

		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
		/// </summary>
		/// <filterpriority>2</filterpriority>
		public void Dispose()
		{
			myIsRunning = false;
			if (myReceivingThread != null)
			{
				myReceivingThread.Interrupt();
				myReceivingThread.Abort();
			}
		}
		
		private void beginReceiving()
		{
			myReceivingThread = new Thread(receivingThread);
			myReceivingThread.Start();
		}
		
		private void receivingThread()
		{
			myIsRunning = true;
			UdpClient client = new UdpClient(PORT);
			IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);

			try
			{
				while (myIsRunning)
				{
					//client.BeginReceive(receiving, client);
					byte[] data = client.Receive(ref endPoint);
					IMessage msg = mySerializeService.Deserialize<IMessage>(data);
					myReceivedMessages.Add(msg);
				}
			}
			finally
			{
				client.Close();
			}
		}

		private void receiving(IAsyncResult ar)
		{
			UdpClient client = (UdpClient) ar.AsyncState;
			
		}
	}
}
